package com.lmscn.lms.api.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.JsonKit;

import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Czl on 2015/9/10.
 */
public class LeiTaiController extends Controller {

    /**
     * 每周一擂
     * 列表
     */
    public void leitaiList() {
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
        Long studentId = getParaToLong("studentId");
        List<LeiTai> leiTaiList = LeiTai.dao.getLeitaiList();
        for (int i = 0; i < leiTaiList.size(); i++) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            Long count = LeiTaiStudent.dao.getJoinLeiTaiCount(leiTaiList.get(i).getLong("id"));
            LeiTaiStudent leiTaiStudent = LeiTaiStudent.dao.getIfJoinLeiTai(studentId, leiTaiList.get(i).getLong("id"));
            if(leiTaiStudent != null ) {
                dataMap.put("join_flag", 1);
            }else{
                dataMap.put("join_flag", 0);
            }
            leiTaiList.get(i).set("img",CommonUtil.getLeiImgUrl(leiTaiList.get(i)));
            dataMap.put("leiTai", leiTaiList.get(i));
            dataMap.put("joinCount",count);
            dataMapList.add(dataMap);
        }
        renderJson(JsonKit.listToJson(dataMapList, 39));
    }
    /**
     * 进入每周一擂
     * 获取擂台设置详情
     */
   /* public void enterLeitai(){
        Map<String,Object> dataMap = new HashMap<String,Object>();
        Long studentId = getParaToLong("studentId");
        LeiTai leiTai = LeiTai.dao.getLast();
        if(leiTai != null){
            dataMap.put("leiTai",leiTai);
            dataMap.put("error_code",0);
        }else{
            dataMap.put("error_code",1);
            dataMap.put("msg","暂无擂台");
        }
        renderJson(JsonKit.mapToJson(dataMap,39));
    }*/

    /**
     * 进入擂台
     */
    public void enterLeitai() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Long studentId = getParaToLong("studentId");
        Long leitaiId = getParaToLong("leitaiId");
        LeiTai leiTai = LeiTai.dao.findById(leitaiId);
        dataMap.put("leiTai", leiTai);
        dataMap.put("error_code", 0);
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 进入擂台,开始答题
     * 生成试题
     */
    public void buildLeiTai() {
        Long studentId = getParaToLong("studentId");
        Long leitaiId = getParaToLong("leitaiId");
        LeiTai leiTai = LeiTai.dao.findById(leitaiId);
        List list = new ArrayList();
        Map<String, Object> finalMap = new HashMap<String, Object>();//最终容器
        Map<String, Object> dataMap = new HashMap<String, Object>();
        // 题库ID
        String categoryIds = leiTai.getStr("question_category_ids");
        // 题目数量
        int questionNum = leiTai.getInt("question_limit_count");
        int totalScore = 100;
        int perScore = totalScore / questionNum;
        List<Question> questionList = Question.dao.getQuestions("single_choice", leiTai.getInt("question_limit_count"), categoryIds);

        //把选项赋给题目
        for (int i = 0; i < questionList.size(); i++) {
            Question question = questionList.get(i);
            List questionMetasList = QuestionMetas.dao.getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
            for (int j = 0; j < questionMetasList.size(); j++) {
                QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
                question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
                question.set("score", perScore);
            }
            list.add(question);
        }
        dataMap.put("question", list);
        dataMap.put("leitaiId", leiTai.getLong("id"));
        finalMap.put("leiTai", dataMap);
        renderJson(JsonKit.mapToJson(finalMap, 39));
    }

    /**
     * 提交攻擂结果
     */
    @Before(Tx.class)
    public void leitaiSubmit() {
        Long studentId = getParaToLong("studentId");
        Long leitaiId = getParaToLong("leitaiId");
        int usedTimes = getParaToInt("usedTime");
        int rightCount = getParaToInt("rightCount");
        int totalScore = getParaToInt("totalScore");
        // 擂台信息
        LeiTai leiTai = LeiTai.dao.findById(leitaiId);
        // 是否之前有攻擂记录
        LeiTaiStudent leiTaiStudent = LeiTaiStudent.dao.findByStuIdAndLeiId(studentId, leitaiId);
        // 学员信息
        Student student = Student.dao.findById(studentId);
        if (leiTaiStudent == null) {
            LeiTaiStudent ltStudent = new LeiTaiStudent();
            LeiTaiStudent.dao.saveLeiTai(ltStudent, leitaiId, studentId, student.getStr("name"), rightCount, totalScore,
                    leiTai.getInt("question_limit_count"), usedTimes, 1);
        } else {
            if (rightCount > leiTaiStudent.getInt("right_count")) {
                leiTaiStudent.set("right_count", rightCount);
                leiTaiStudent.set("score", totalScore);
                leiTaiStudent.set("used_time", usedTimes);
                leiTaiStudent.set("gonglei_times", leiTaiStudent.getInt("gonglei_times") + 1);
                leiTaiStudent.set("start_time", new Date());
                leiTaiStudent.update();
            }
        }
        // 跳转结果页面参数
        Long fightSuccessCount = LeiTaiStudent.dao.fightSuccessCount(leitaiId, rightCount, studentId);
        Long joinCount = LeiTaiStudent.dao.joinLeiNotContainSelf(leitaiId, studentId);
        double fightPer = 0.0;
        if (joinCount == 0L) {
            fightPer = 1;
        } else {
            fightPer = (double) fightSuccessCount / (double) joinCount;
        }
        DecimalFormat df = new DecimalFormat("#");
        String fight = df.format(fightPer * 100);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("usedTime", usedTimes);
        dataMap.put("rightCount", rightCount);
        dataMap.put("totalScore", totalScore);
        dataMap.put("fightPercent", fight);
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 攻擂排行榜
     */
    public void leiRank() {
        Long studentId = getParaToLong("studentId");
        Long leitaiId = getParaToLong("leitaiId");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        LeiTaiStudent leiTaiStudent = LeiTaiStudent.dao.findByStuIdAndLeiId(studentId, leitaiId);
        if (leiTaiStudent != null) {
            // 本擂台的学员列表
            List<LeiTaiStudent> leiTaiStudents = LeiTaiStudent.dao.findLeiStudent(leitaiId, 30);
            for(int i=0;i<leiTaiStudents.size();i++){
                Student student = Student.dao.findById(leiTaiStudents.get(i).getLong("student_id"));
                leiTaiStudents.get(i).set("head_img", CommonUtil.getHeadImgUrl(student));
            }
            // 排名，击败百分比
            Long fightSuccessCount = LeiTaiStudent.dao.fightSuccessCount(leitaiId, leiTaiStudent.getInt("right_count"), studentId);
            Long joinCount = LeiTaiStudent.dao.joinLeiNotContainSelf(leitaiId, studentId);
            double fightPer = 0.0;
            if (joinCount == 0L) {
                fightPer = 1;
            } else {
                fightPer = (double) fightSuccessCount / (double) joinCount;
            }
            DecimalFormat df = new DecimalFormat("#");
            String fight = df.format(fightPer * 100);
            Long stuRank = LeiTaiStudent.dao.stuRank(leitaiId, leiTaiStudent.getInt("right_count"));
            dataMap.put("leiStuList", leiTaiStudents);
            dataMap.put("fightPercent", fight);
            dataMap.put("myRankNum", stuRank + 1L);
            dataMap.put("error_code", 0);
        } else {
            dataMap.put("error_code", 1);
            dataMap.put("msg", "还未参加本攻擂");
        }
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

}
